{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "stonk.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "metadata": {
        "id": "GvBGrqZhfybl"
      },
      "source": [
        "import pandas_datareader as web\n",
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "import math\n",
        "import pandas as pd\n",
        "from sklearn.preprocessing import MinMaxScaler\n",
        "from keras.models import Sequential\n",
        "from keras.layers import  LSTM, Dense\n",
        "import csv\n",
        "\n",
        "plt.style.use('fivethirtyeight')\n",
        "df = web.DataReader('RELIANCE.NS', data_source='yahoo', start='2015-01-01', end='2021-03-09')\n",
        "#using YahooFinance API to fetch data about the historical price of the stock\n",
        "\n",
        "\n",
        "df\n",
        "\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nB7ufawSIDEX"
      },
      "source": [
        "\n",
        "close = df.filter(['Close'])\n",
        "\n",
        "#close.fillna(method='ffill') #fills the values of the N/A datas with that of the pervious data. e.g. sat sun will have closing price of friday\n",
        "\n",
        "fig_size = plt.rcParams[\"figure.figsize\"]\n",
        "fig_size[0] = 20\n",
        "fig_size[1] = 4\n",
        "plt.rcParams[\"figure.figsize\"] = fig_size\n",
        "plt.xlabel('Date')\n",
        "plt.ylabel('Closing Price')\n",
        "\n",
        "plt.grid(True)\n",
        "plt.plot(close)\n",
        "plt.show()\n",
        "\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "LJ6lJ3gPJBEi"
      },
      "source": [
        "dataset = close.values #convers the dataframe into numpy array\n",
        "#get the no of rows to train the model on\n",
        "train_data_len = math.ceil(len(dataset)*.8)\n",
        "train_data_len\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "XDcDeGvHL0XY"
      },
      "source": [
        "#scaling the data\n",
        "scaler = MinMaxScaler(feature_range=(0,1))\n",
        "scaled_data = scaler.fit_transform(dataset)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "B9wZ70kGN9zr"
      },
      "source": [
        "#creating trainging data\n",
        "#creating scaled training dataset\n",
        "train_data = scaled_data[0:train_data_len,:]\n",
        "#splitting the data into x_train and y_train dataset\n",
        "x_train = []\n",
        "y_train = [] # this will be the 60th(for this) value which out model will predict \n",
        "\n",
        "for i in range(60, len(train_data)): #appends from 60 to n, second look will predict the 61st day, 3rd the 62nd day... so each day is trained\n",
        "  x_train.append(train_data[i-60:i, 0])\n",
        "  y_train.append(train_data[i,0])\n",
        "\n",
        "\n",
        "#converting x_train and y_train to numpy arrays\n",
        "x_train, y_train = np.array(x_train), np.array(y_train)\n",
        "\n",
        "#reshaping data (lstm model expects 3D data)\n",
        "x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\n",
        "x_train.shape"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "5bzS6O2tSYl-"
      },
      "source": [
        "#lstm model\n",
        "model = Sequential()\n",
        "model.add(LSTM(units= 50, return_sequences=True, input_shape = (x_train.shape[1],1)))\n",
        "model.add(LSTM(units= 50, return_sequences=False))\n",
        "model.add(Dense(units= 25))\n",
        "model.add(Dense(units= 1))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "7MDublg7WoVb"
      },
      "source": [
        "#compile model\n",
        "model.compile(optimizer = 'adam', loss = 'mean_squared_error')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ilA8llEZW-bz"
      },
      "source": [
        "#train the model\n",
        "model.fit(x_train, y_train, batch_size= 1, epochs= 2)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vMVdebCMYpsb"
      },
      "source": [
        "#creating testing data set \n",
        "#creating a new array containing remaining data from the data set\n",
        "test_data = scaled_data[train_data_len -60: , :]\n",
        "\n",
        "x_test = []\n",
        "y_test = dataset[train_data_len :, :]\n",
        "\n",
        "for i in range(60, len(test_data)):\n",
        "  x_test.append(test_data[i-60:i, 0])\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "NI2Z7Al3aaxL"
      },
      "source": [
        "#converting x_test to numpy arrays\n",
        "x_test = np.array(x_test)\n",
        "\n",
        "#reshaping data (lstm model expects 3D data)\n",
        "x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))\n",
        "x_test.shape"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ehZrb38Wa6GZ"
      },
      "source": [
        "#get the model's price predicted values \n",
        "predictions = model.predict(x_test)\n",
        "predictions = scaler.inverse_transform(predictions)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6Der0FZybSgW"
      },
      "source": [
        "#get the root mean square error(RMSE)\n",
        "rmse=np.sqrt(np.mean(((predictions- y_test)**2)))\n",
        "rmse"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ueHPaZRx18Vs"
      },
      "source": [
        "#plot the data\n",
        "train = close[:train_data_len]\n",
        "valid = close[train_data_len:]\n",
        "valid['Predictions'] = predictions\n",
        "\n",
        "plt.figure(figsize = (20,8))\n",
        "plt.title('Model')\n",
        "plt.xlabel('Date', fontsize= 18)\n",
        "plt.ylabel('Closing Price', fontsize= 18)\n",
        "\n",
        "plt.grid(True)\n",
        "plt.plot(train['Close'])\n",
        "plt.plot(valid[['Close', 'Predictions']])\n",
        "plt.legend(['Training Data', 'Actual Value', 'Prediction'], loc= 'upper left')\n",
        "plt.show()\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1LOBh8u_wWwo"
      },
      "source": [
        "valid"
      ],
      "execution_count": null,
      "outputs": []
    }
  ]
}